<template>
 <div class="page_container">
     <van-form>
         <van-field
             v-model="title"
             name="标题"
             label="标题"
             placeholder="请输入标题"
             :rules="[{ required: true, message: '请输入标题'}]"
         />
         <van-field
             readonly
             v-model="categoryDisplay"
             name="分类"
             label="分类"
             placeholder="请选择分类"
             :rules="[{ required: true, message: '请选择分类' }]"
             @click="categoryPickerShow = true"
         />
         <van-popup v-model="categoryPickerShow" round position="bottom">
             <van-picker
                 show-toolbar
                 :columns="categoryOptions.map(v => v.name)"
                 @cancel="categoryPickerShow = false"
                 @confirm="(e) => {category = categoryOptions.find(v => v.name === e).id; categoryPickerShow = false;}"
             />
         </van-popup>
         <van-field
             readonly
             name="文章正文"
             label="文章正文"
             :placeholder="content.length === 0 ? '点击编写正文' : `${content.length} 字，点击编辑`"
             @click="showEditorPop = true"
         />
         <van-popup v-model="showEditorPop" position="top" style="height: 100%; width: 100%;">
             <div class="toolbar">
                 <van-button size="small" type="primary" @click="showEditorPop = false">完成</van-button>
             </div>
             <Editor
                 :editorChange="editorChange"
                 :content.sync="content"
                 :extraStyle="{height: '93vh'}"
             ></Editor>
         </van-popup>
         <van-field
             v-model="url"
             name="url"
             label="URL"
             placeholder="请输入 url"
             :rules="[{ required: true, message: '请输入 url' }]"
         />
         <p class="tip">url 是为了更好的 SEO 效果，如果不填写，则使用文章 id</p>
         <van-field
             readonly
             v-model="create_time"
             name="创建日期"
             label="创建日期"
             placeholder="点击选择创建日期"
             @click="showCreateTimePop = true"
         />
         <van-popup v-model="showCreateTimePop" round position="bottom">
             <van-datetime-picker
                 type="date"
                 title="选择年月日"
                 placeholder="请选择分类"
                 @confirm="(e) => { create_time = `${e.getFullYear()}-${e.getMonth() + 1}-${e.getDate()}`; showCreateTimePop = false}"
             />
         </van-popup>
         <p class="tip">如果不指定创建日期，则默认为发布时间</p>
         <div class="submit-btns">
             <van-button v-show="id > 0" round block @click="$router.back()">取消</van-button>
             <van-button round block type="info" :loading="loading" @click="onSubmitClick">提交</van-button>
         </div>
     </van-form>
 </div>
</template>

<script>
import { getCategoryList, addCategory, addNewBlog, getBlogRow, saveBlog } from '../../../api/blog.js'
import { openBlogPage } from '@/utils/url'
import Editor from '~/editor'

export default {
    name: 'Newblog',
    components: { Editor },
    data() {return {
        id: 0,
        title: '',
        categoryOptions: [],
        content: '',
        contentHtml: '',
        category: '',
        loading: false,
        url: '',
        newCategory: {
            show: false,
            name: '',
            loading: false
        },
        create_time: '',

        // 页面js统一，下面是移动端的变量
        categoryPickerShow: false,
        showEditorPop: false,
        showCreateTimePop: false
    }},
    created() {
        this.getOptions()
    },
    mounted() {
        const id = this.$route.query.id
        if (id) {
            this.loading = true
            getBlogRow({id: id}).then(res => {
                this.loading = false
                this.id = res.data.id
                this.category = res.data.category
                this.contentHtml = res.data.content_html
                this.content = res.data.content_md
                this.title = res.data.title
                this.url = res.data.url
                this.create_time = res.data.create_time
            }).catch(e => {
                this.loading = false
                this.$message.error(e.msg)
            })
        }
    },
    methods: {
        /**
         * 获取分类
         */
        getOptions() {
            getCategoryList().then(res => {
                this.categoryOptions = res.data
                this.category = res.data[res.data.length - 1] ? res.data[res.data.length - 1].id : ''
            }).catch(e => {
                console.error(e);
                this.$message.error(e.msg)
            })
        },
        /**
         * 编辑器值变化回调
         * v 原文
         * h 解析后的 html
         */
        editorChange(v, h) {
            this.contentHtml = h
        },
        /**
         * 提交新建分类
         */
        newCategoryCommit() {
            this.newCategory.loading = true
            addCategory({name: this.newCategory.name}).then(res => {
                this.newCategory.loading = false
                this.getOptions()
                this.newCategory.show = false
            }).catch(e => {
                this.newCategory.loading = false
                this.$message.error(e.msg)
            })
        },

        /**
         * 发布按钮点击
         */
        onSubmitClick() {
            console.log(this.title, this.content, this.category, this.contentHtml);
            this.loading = true
            if (this.id > 0) {
                const data = {
                    id: this.id,
                    title: this.title,
                    content_md: this.content,
                    category: this.category,
                    content_html: this.contentHtml,
                    url: this.url ? this.url : ''
                }
                if (this.create_time) {
                    data.create_time = this.create_time
                }
                saveBlog(data).then(res => {
                    this.loading = false
                    this.$message.success('保存成功')
                    // setTimeout(() => {
                    //     openBlogPage(this.url ? this.url : res.data)
                    //     this.$router.push('/blog/blogs')
                    // }, 1000);
                }).catch(e => {
                    this.loading = false
                    this.$message.error(e.msg)
                })
            } else {
                const data = {
                    title: this.title,
                    content_md: this.content,
                    category: this.category,
                    content_html: this.contentHtml,
                    url: this.url ? this.url : ''
                }
                if (this.create_time) {
                    data.create_time = this.create_time
                }
                addNewBlog(data).then(res => {
                    this.loading = false
                    this.$message.success('发表成功')
                    // setTimeout(() => {
                    //     openBlogPage(this.url ? this.url : res.data)
                    //     this.$router.push('/blog/blogs')
                    // }, 1000);
                }).catch(e => {
                    this.loading = false
                    this.$message.error(e.msg)
                })
            }
        }
    },
    computed: {
        categoryDisplay() {
            const category = this.categoryOptions.find(v => v.id === this.category)
            return category && category.name ? category.name : ''
        }
    }
}
</script>

<style scoped>
.toolbar {
    height: 7vh;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    padding: 0 10px;
}
.tip {
    font-size: 13px;
    color: gray;
    margin-left: 20px;
}
.submit-btns {
    margin: 16px;
    display: flex;
    flex-direction: row;
}
</style>
